#!/usr/bin/env python3
"""
字符串排列算法测试运行器

这个脚本提供了多种测试模式：
1. 基本演示：展示各种算法的基本用法
2. 自定义性能测试：使用自研的性能测试框架 (支持资源限制)
3. pytest基准测试：使用 pytest-benchmark 专业框架
4. 内存分析：使用 memory_profiler 进行内存分析
5. 精确时间测试：使用 timeit 进行精确计时
6. 性能分析：使用 cProfile 进行详细性能分析
7. 资源限制测试：演示不同资源限制级别的效果
"""

import sys
import os
import subprocess
from resource_monitor import CONSERVATIVE_LIMITS, MODERATE_LIMITS, AGGRESSIVE_LIMITS


def check_dependencies():
    """检查测试依赖"""
    dependencies = {
        'pytest': 'pytest',
        'pytest-benchmark': 'pytest-benchmark', 
        'memory_profiler': 'memory_profiler',
        'psutil': 'psutil'
    }
    
    missing = []
    for package, pip_name in dependencies.items():
        try:
            __import__(package.replace('-', '_'))
        except ImportError:
            missing.append(pip_name)
    
    if missing:
        print("⚠️  缺少以下依赖包:")
        for pkg in missing:
            print(f"   - {pkg}")
        print("\n安装命令:")
        print(f"pip install {' '.join(missing)}")
        print("\n注意: 基本演示和自定义性能测试不需要额外依赖")
        return False
    return True


def run_basic_demo():
    """运行基本算法演示"""
    print("🎯 运行基本算法演示...")
    print("=" * 50)
    
    from string_permutation import main
    main()


def run_custom_performance_test():
    """运行自定义性能测试"""
    print("🚀 运行自定义性能测试...")
    print("=" * 50)
    
    from performance_test import PerformanceTest
    perf_test = PerformanceTest(MODERATE_LIMITS)
    perf_test.run_performance_test()


def run_custom_performance():
    """运行自定义性能测试（别名）"""
    run_custom_performance_test()


def run_custom_performance_with_limits(limits_type="moderate"):
    """运行带资源限制的自定义性能测试"""
    limits_map = {
        "conservative": CONSERVATIVE_LIMITS,
        "moderate": MODERATE_LIMITS, 
        "aggressive": AGGRESSIVE_LIMITS
    }
    
    limits = limits_map.get(limits_type, MODERATE_LIMITS)
    limit_names = {
        "conservative": "保守",
        "moderate": "适中",
        "aggressive": "激进"
    }
    
    print(f"🔧 运行{limit_names.get(limits_type, '适中')}资源限制的性能测试...")
    print("=" * 50)
    print(f"📊 资源限制配置:")
    print(f"   最大内存: {limits.max_memory_mb} MB")
    print(f"   最大执行时间: {limits.max_execution_time} 秒")
    print(f"   最大字符串长度: {limits.max_string_length}")
    print(f"   最大阶乘值: {limits.max_factorial:,}")
    print("=" * 50)
    
    from performance_test import PerformanceTest
    perf_test = PerformanceTest(limits)
    perf_test.run_performance_test()


def run_pytest_benchmark():
    """运行 pytest 基准测试"""
    print("⚡ 运行 pytest 基准测试...")
    print("=" * 50)
    
    if not check_dependencies():
        return
    
    print("执行命令: pytest benchmark_test.py -v --benchmark-only")
    result = subprocess.run([
        sys.executable, "-m", "pytest", 
        "benchmark_test.py", "-v", "--benchmark-only"
    ], capture_output=False)
    
    if result.returncode != 0:
        print("❌ pytest 基准测试执行失败")
    else:
        print("✅ pytest 基准测试完成")


def run_memory_analysis():
    """运行内存分析"""
    print("💾 运行内存分析...")
    print("=" * 50)
    
    try:
        import memory_profiler
        from memory_profile_test import run_memory_tests
        run_memory_tests()
    except ImportError:
        print("❌ 缺少 memory_profiler 依赖")
        print("安装: pip install memory_profiler psutil")


def run_timeit_test():
    """运行精确时间测试"""
    print("⏱️  运行精确时间测试...")
    print("=" * 50)
    
    from timeit_test import run_timeit_tests
    run_timeit_tests()


def run_cprofile_analysis():
    """运行 cProfile 性能分析"""
    print("🔬 运行 cProfile 性能分析...")
    print("=" * 50)
    
    from cprofile_test import run_cprofile_tests
    run_cprofile_tests()


def run_all_tests():
    """运行所有测试"""
    print("🌟 运行所有测试...")
    print("=" * 80)
    
    tests = [
        ("基本演示", run_basic_demo),
        ("自定义性能测试", run_custom_performance_test),
        ("timeit 精确计时", run_timeit_test),
        ("cProfile 性能分析", run_cprofile_analysis),
        ("内存分析", run_memory_analysis),
        ("pytest 基准测试", run_pytest_benchmark),
    ]
    
    for i, (name, func) in enumerate(tests, 1):
        print(f"\n{i}/{len(tests)} - {name}")
        print("=" * 60)
        try:
            func()
        except Exception as e:
            print(f"❌ {name} 执行失败: {e}")
        
        if i < len(tests):
            input("\n按 Enter 继续下一个测试...")


def show_advanced_commands():
    """显示高级测试命令"""
    print("\n🔧 高级测试命令")
    print("=" * 50)
    print("资源限制测试:")
    print("  python performance_test.py conservative  # 保守限制")
    print("  python performance_test.py moderate     # 适中限制")
    print("  python performance_test.py aggressive   # 激进限制")
    
    print("\npytest 相关:")
    print("  pytest benchmark_test.py --benchmark-sort=mean")
    print("  pytest benchmark_test.py --benchmark-json=results.json")
    print("  pytest benchmark_test.py --benchmark-histogram")
    print("  pytest benchmark_test.py --benchmark-compare=baseline.json")
    
    print("\nmemory_profiler 相关:")
    print("  python -m memory_profiler memory_profile_test.py")
    print("  mprof run memory_profile_test.py")
    print("  mprof plot")
    
    print("\ncProfile 相关:")
    print("  python -m cProfile -s cumtime cprofile_test.py")
    print("  python -m pstats profile_递归方法.prof")
    print("  snakeviz profile_递归方法.prof  # 需要: pip install snakeviz")
    
    print("\n资源监控演示:")
    print("  python resource_monitor.py  # 查看不同字符串长度的资源预估")
    
    print("\n可视化工具:")
    print("  pip install snakeviz  # cProfile 结果可视化")
    print("  pip install py-spy     # 实时性能监控")
    print("  pip install line_profiler  # 逐行性能分析")


def main():
    """主菜单"""
    print("📚 字符串排列算法综合测试套件")
    print("=" * 60)
    print("选择测试模式:")
    print("1. 基本演示 - 展示各种算法的基本用法")
    print("2. 自定义性能测试 - 使用内置的性能测试框架")
    print("3. pytest 基准测试 - 使用 pytest-benchmark 专业框架")
    print("4. 内存分析 - 使用 memory_profiler 分析内存使用")
    print("5. 精确时间测试 - 使用 timeit 进行精确计时")
    print("6. 性能分析 - 使用 cProfile 进行详细性能分析")
    print("7. 运行所有测试 - 依次执行所有测试模式")
    print("8. 显示高级命令 - 查看更多专业测试命令")
    print("0. 退出")
    print("=" * 60)
    
    while True:
        try:
            choice = input("请输入选择 (0-8): ").strip()
            
            if choice == "0":
                print("👋 退出测试套件")
                break
            elif choice == "1":
                run_basic_demo()
                break
            elif choice == "2":
                # 提供资源限制选项
                print("\n🔧 选择资源限制级别:")
                print("1. 保守限制 (最大内存100MB, 最大长度6)")
                print("2. 适中限制 (最大内存500MB, 最大长度8) [默认]")
                print("3. 激进限制 (最大内存1000MB, 最大长度10)")
                
                limit_choice = input("请选择 (1-3, 回车默认2): ").strip()
                if limit_choice == "1":
                    run_custom_performance_with_limits("conservative")
                elif limit_choice == "3":
                    run_custom_performance_with_limits("aggressive")
                else:
                    run_custom_performance_with_limits("moderate")
                break
            elif choice == "3":
                run_pytest_benchmark()
                break
            elif choice == "4":
                run_memory_analysis()
                break
            elif choice == "5":
                run_timeit_test()
                break
            elif choice == "6":
                run_cprofile_analysis()
                break
            elif choice == "7":
                run_all_tests()
                break
            elif choice == "8":
                show_advanced_commands()
                break
            else:
                print("❌ 无效选择，请输入 0-8")
                
        except KeyboardInterrupt:
            print("\n👋 用户中断，退出测试套件")
            break
        except Exception as e:
            print(f"❌ 发生错误: {e}")
            break


if __name__ == "__main__":
    # 检查命令行参数
    if len(sys.argv) > 1:
        arg = sys.argv[1].lower()
        if arg in ["demo", "basic", "1"]:
            run_basic_demo()
        elif arg in ["custom", "perf", "performance", "2"]:
            # 检查是否有资源限制参数
            if len(sys.argv) > 2:
                limits_type = sys.argv[2].lower()
                run_custom_performance_with_limits(limits_type)
            else:
                run_custom_performance()
        elif arg in ["pytest", "benchmark", "3"]:
            run_pytest_benchmark()
        elif arg in ["memory", "mem", "4"]:
            run_memory_analysis()
        elif arg in ["timeit", "time", "5"]:
            run_timeit_test()
        elif arg in ["cprofile", "profile", "6"]:
            run_cprofile_analysis()
        elif arg in ["all", "everything", "7"]:
            run_all_tests()
        elif arg in ["advanced", "commands", "8"]:
            show_advanced_commands()
        elif arg in ["conservative", "moderate", "aggressive"]:
            # 直接运行指定资源限制的测试
            run_custom_performance_with_limits(arg)
        else:
            print("用法:")
            print("  python run_tests.py                      # 交互式菜单")
            print("  python run_tests.py demo                 # 基本演示")
            print("  python run_tests.py custom               # 自定义性能测试")
            print("  python run_tests.py custom conservative  # 保守资源限制测试")
            print("  python run_tests.py custom moderate      # 适中资源限制测试")
            print("  python run_tests.py custom aggressive    # 激进资源限制测试")
            print("  python run_tests.py conservative         # 直接保守限制测试")
            print("  python run_tests.py moderate             # 直接适中限制测试")
            print("  python run_tests.py aggressive           # 直接激进限制测试")
            print("  python run_tests.py pytest               # pytest 基准测试")
            print("  python run_tests.py memory               # 内存分析")
            print("  python run_tests.py timeit               # 精确时间测试")
            print("  python run_tests.py cprofile     # 性能分析")
            print("  python run_tests.py all          # 运行所有测试")
            print("  python run_tests.py advanced     # 显示高级命令")
    else:
        main()
